# coding: utf-8
# Filename : get_pv_uv.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-
import sys,datetime
import os,commands

log_path = '/opt/log/'
#日志发送人员列表
toAdd = ['qyhdt@sina.com']

email_model_pv_uv = '''<table style="font-size:12px; text-align:center; border:solid 1px gray;"cellspacing="0" width="700px" height="50px;" >
	<tr bgcolor="#FFFF99">
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">时间</td>
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">请求PV</td>
		<td width="10%" style="border-bottom:solid gray 1px;">请求UV</td>
	</tr>
	<tr border-bottom:solid gray 1px;>
		<td width="10%" style="border-right:solid gray 1px; border-top: solid gray 1px;">{1}</td>
		<td width="10%" style="border-right:solid gray 1px; border-top: solid gray 1px;">{2}</td>
		<td width="10%" style="border-top: solid gray 1px;">{3}</td>
	</tr>
</table>
'''
email_model_ip = '''<table style="font-size:12px; text-align:center; border:solid 1px gray;"cellspacing="0" width="700px" height="50px;" >
	<tr bgcolor="#FFFF99">
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">时间</td>
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">来自IP</td>
		<td width="10%" style="border-bottom:solid gray 1px;">请求次数</td>
	</tr>
	{table_data}
</table>
'''

email_model_page = '''<table style="font-size:12px; text-align:center; border:solid 1px gray;"cellspacing="0" width="700px" height="50px;" >
	<tr bgcolor="#FFFF99">
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">时间</td>
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">请求页面</td>
		<td width="10%" style="border-bottom: solid gray 1px;">请求次数</td>
	</tr>
	{table_data}
</table>
'''
email_model_num = '''<table style="font-size:12px; text-align:center; border:solid 1px gray;"cellspacing="0" width="700px" height="50px;" >
	<tr bgcolor="#FFFF99">
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">时间</td>
		<td width="10%" style="border-right:solid gray 1px; border-bottom:solid gray 1px;">手机号码</td>
		<td width="10%" style="border-bottom:solid gray 1px;">请求次数</td>
	</tr>
	{table_data}
</table>
'''
email_model_in = '''<tr border-bottom:solid gray 1px;>
		<td width="10%" style="border-right:solid gray 1px; border-top: solid gray 1px;">{1}</td>
		<td width="10%" style="border-right:solid gray 1px; border-top: solid gray 1px;">{2}</td>
		<td width="10%" style="border-top: solid gray 1px;">{3}</td>
	</tr>
'''
div = '''<div style="height: 10px; width: 5px;"></div>'''

system_author = '''<div style="font-size:12px; color:gray; padding-top:20px; width: 700px; text-align:right;">注：此邮件为系统自动发送，请勿回复！{prefix}</div>'''

def getYesterday():   
    today=datetime.date.today()   
    oneday=datetime.timedelta(days=1)   
    yesterday=today-oneday   
    return yesterday

#日期设定
yesterday = getYesterday()
if len(sys.argv) >= 2:
    yesterday = sys.argv[1]
yesterday = str(yesterday)

print yesterday + '---统计信息'

pv_shell = 'grep "" %saccess_log.%s -c' % (log_path, yesterday)
(a, b) = commands.getstatusoutput(pv_shell)
pv = int(b) - 1
print 'pv:',pv

uv_shell = '''grep "" %saccess_log.%s | awk -F '`' '{print $2 | "sort -u"}' | wc -l''' % (log_path, yesterday)
(a, b) = commands.getstatusoutput(uv_shell)
uv = int(b) - 1
print 'uv:',uv

pv_uv_info_str = email_model_pv_uv.replace('{1}', yesterday).replace('{2}', str(pv)).replace('{3}', str(uv))
pv_uv_info_str += div

common_dimensionality_shell = '''awk -F '`' '{print $5}' %saccess_log.%s | awk -F ';' '{print %s}' | awk -F ':' '{print $2}' | sort | uniq -c'''
phone_dimensionality_shell = common_dimensionality_shell % (log_path, yesterday, '$1')
brand_dimensionality_shell = common_dimensionality_shell % (log_path, yesterday, '$2')
ip_count_dimensionality_shell = '''grep "" %saccess_log.%s | awk -F '`' '{print $2}' | sort | uniq -c''' % (log_path, yesterday)
page_count_dimensionality_shell = '''grep "" %saccess_log.%s | awk -F '`' '{print $3}' | sort | uniq -c''' % (log_path, yesterday)

#获取html信息
def getHtmlInfo(b):
	obj_count_info = str(b)
	obj_count_array = obj_count_info.splitlines()
	obj_info_str = ''
	for obj in obj_count_array:
		obj = str(obj).strip()
		obj_count_array = obj.split(' ')
		if len(obj_count_array) > 1:
			obj_info_str += email_model_in.replace('{1}', yesterday).replace('{2}', obj_count_array[1]).replace('{3}', obj_count_array[0])
	return obj_info_str

#-------------IP访问统计--------------
(a, b) = commands.getstatusoutput(ip_count_dimensionality_shell)
ip_info_str = getHtmlInfo(b)
ip_info_str = email_model_ip.replace('{table_data}', ip_info_str) + div
			
		
	
#-------------页面访问统计--------------
(a, b) = commands.getstatusoutput(page_count_dimensionality_shell)
page_info_str = getHtmlInfo(b)
page_info_str = email_model_page.replace('{table_data}', page_info_str) + div		


#-------------号码访问统计--------------
(a, b) = commands.getstatusoutput(phone_dimensionality_shell)
num_info_str = getHtmlInfo(b)
num_info_str = email_model_num.replace('{table_data}', num_info_str) + div	

#-------------机型访问统计--------------
(a, b) = commands.getstatusoutput(brand_dimensionality_shell)
print '-------------机型维度统计--------------'
print str(b)







import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):
        strFrom = fromAdd
        strTo = ', '.join(toAdd)
        server = authInfo.get('server')
        user = authInfo.get('user')
        passwd = authInfo.get('password')
        if not (server and user and passwd) :
                print 'incomplete login info, exit now'
                return
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        msgRoot['From'] = strFrom
        msgRoot['To'] = strTo
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)
        msgText = MIMEText(plainText, 'plain', 'utf-8')
        msgAlternative.attach(msgText)
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText)
        smtp = smtplib.SMTP()
        smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, toAdd, msgRoot.as_string())
        smtp.quit()
        return


#发送统计结果邮件
def send_statistics(content):
	title = '--statistics result'
	subject = str(yesterday) + title
	plainText = content
	htmlText = content
	sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)


#邮件发送
#邮件服务器设定
authInfo = {}
authInfo['server'] = 'smtp.sina.com'
authInfo['user'] = 'sys_auto_run'
authInfo['password'] = '1234567890'
fromAdd = 'sys_auto_run@sina.com'

email_info = pv_uv_info_str + ip_info_str + page_info_str + num_info_str

email_info += system_author.replace('{prefix}', 'ROSE AUTO EMAIL SYSTEM')

send_statistics(email_info)

